package com.thiswhyme.seata.storage.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thiswhyme.common.expection.BusinessException;
import com.thiswhyme.seata.storage.domain.Product;
import com.thiswhyme.seata.storage.repository.ProductMapper;

import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: thiswhyme
 * @date: 2020/9/4
 */
@Slf4j
@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Transactional(rollbackFor = Exception.class)
    public boolean reduceStock(Long productId, Integer requiredAmount) {
        log.info("当前 XID: {}", RootContext.getXID());
        checkStock(productId, requiredAmount);

        log.info("开始扣减 {} 库存", productId);
        Integer record = productMapper.reduceStock(productId, requiredAmount);
        log.info("扣减 {} 库存结果:{}", productId, record > 0 ? "操作成功" : "扣减库存失败");
        return record > 0;
    }

    public void checkStock(Long productId, Integer requiredAmount) {
        log.info("检查 {} 库存", productId);
        Product product = productMapper.selectById(productId);
        if (null == product) {
            log.warn("商品{} 不存在", productId);
            throw new BusinessException("商品不存在");
        }
        if (null != product && product.getStock() < requiredAmount) {
            log.warn("{} 库存不足，当前库存:{}", productId, product.getStock());
            throw new BusinessException("库存不足");
        }
    }
}
